package com.smalldoor.thread.demo02;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

public class Callable01 implements Callable<Boolean> {

    private String name;

    private String url;

    public Callable01(String url,String name) {
        this.url = url;
        this.name = name;
    }

    @Override
    public Boolean call() {
        WebDownload webDownload = new WebDownload();
        webDownload.downloadFile(url,name);
        System.out.println("文件已下载，文件名为：" + name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Callable01 t1 = new Callable01("https://pic2.zhimg.com/v2-5fb13110e1de13d4c11e6e7f5b8026da_r.jpg","1.jpg");
        Callable01 t2 = new Callable01("https://img.zcool.cn/community/01a88459ae0d88a801211d250cb394.jpg@1280w_1l_2o_100sh.jpg","2.jpg");
        Callable01 t3 = new Callable01("https://img.zcool.cn/community/018fcb55c2ef8d6ac7253f36f6d34e.jpg@1280w_1l_2o_100sh.jpg","3.jpg");

        ExecutorService service = Executors.newFixedThreadPool(3);

        Future<Boolean> rs1 = service.submit(t1);
        Future<Boolean> rs2 = service.submit(t2);
        Future<Boolean> rs3 = service.submit(t3);

        Boolean r1 = rs1.get();
        Boolean r2 = rs2.get();
        Boolean r3 = rs3.get();


        System.out.println(r1);
        System.out.println(r2);
        System.out.println(r3);

        service.shutdownNow();
    }

    class WebDownload {

        public void downloadFile(String url, String name) {
            try {
                FileUtils.copyURLToFile(new URL(url),new File(name));
            } catch (IOException e) {
                System.out.println("io异常");
                throw new RuntimeException(e);
            }
        }
    }
}
